# -*- coding: UTF-8 -*-
"""
@auth:buxiangjie
@date:2020-05-12 11:26:00
@describe: 修改saas数据的一些接口
"""
import asyncio
import traceback

from app.log.ulog import logger_

from typing import List

from dateutil.relativedelta import relativedelta
from fastapi import (APIRouter, Depends, File, Form, Query, Request, UploadFile, status, Body)

from app.db.conn import DataBasePool
from app.db.db_api import ToolsSql
from app.item.item import OverdueItem, Env, BusiType
from app.scripts.offline_repay import off_repay

router = APIRouter()


@router.get("/", name="首页", status_code=status.HTTP_200_OK)
async def index(env: Env):
	return {"code": 2000, "msg": env}


@router.delete("/removeBusiness", name="删除异常数据")
async def remove_business(env: Env, busi_type: BusiType, lis: List[str]):
	"""
	- env: 数据所在环境 test/qa
	- busi_type: 业务类型 project/asset
	- lis: ID列表[str, str, str, str]
	- 如果是资产,删除asset/asset_fee/asset_extra
	  /overdue/overdue_detail/fee_plan/asset_swap_apply
	  /asset_swap_detail/repayment/repayment_detail
	  /repayment_plan/user_fee_plan/user_repayment_plan
	- 如果是进件,删除project_detail/project_customer_detail
	  /project_enterprise_detail/project_entity_detail
	  /project_extra_detail
	"""
	if (None in lis) or lis == []:
		return {"code": 4000, "msg": "列表不能为空"}
	kwg = {}
	if env.value == "test":
		kwg["saas_db"] = DataBasePool().test_saas
		kwg["data_station_db"] = DataBasePool().test_data_station
	elif env.value == "qa":
		kwg["saas_db"] = DataBasePool().qa_saas
		kwg["data_station_db"] = DataBasePool().qa_data_station
	if busi_type.value == "asset":
		for i in lis:
			asyncio.create_task(ToolsSql.del_asset_data(environment=env.value, asset_id=i, **kwg))
		logger_.info(f"删除异常数据任务开始:{busi_type.value}-{lis}")
		return {"code": 2000, "msg": "异步执行中"}
	elif busi_type.value == "project":
		for i in lis:
			asyncio.create_task(ToolsSql.del_project_data(project_id=i, **kwg))
		logger_.info(f"删除异常数据任务开始:{busi_type.value}-{lis}")
		return {"code": 2000, "msg": "异步执行中"}
	else:
		return {"code": 4000, "msg": "不支持的类型"}


@router.delete("/removeUser", name="删除用户")
async def remove_user(env: Env, source_user_id: List[str] = Body(embed=True)):
	"""
	删除用户(包括用户相关授信/进件/资产)
	:env: 数据所在环境 test/qa
	:source_user_id: 来源用户ID
	"""
	for source in source_user_id:
		project_detail = ToolsSql.select_project(env.value, source)

		if project_detail:
			logger_.info("存在进件")
			with_asset = []
			with_project = []
			only_project = []
			for p in project_detail:
				if p["loan_result"] == 1:
					asset_id = ToolsSql.get_asset_id(env.value, p["id"])
					if asset_id:
						with_asset.append(str(asset_id))
					with_project.append(str(p["id"]))
				else:
					only_project.append(p["id"])
			logger_.info(f"带有资产:{with_asset}")
			logger_.info(f"带有进件:{with_project}")
			logger_.info(f"只有进件:{only_project}")
			if len(with_project) > 0:
				asyncio.create_task(remove_business(env, BusiType.project, with_project))
			if len(with_asset) > 0:
				asyncio.create_task(remove_business(env, BusiType.asset, with_asset))
			if len(only_project) > 0:
				asyncio.create_task(remove_business(env, BusiType.project, only_project))
		else:
			logger_.info("无进件信息")
		kwg = {}
		if env.value == "test":
			kwg["saas_db"] = DataBasePool().test_saas
			kwg["nebula_db"] = DataBasePool().test_nebula
		elif env.value == "qa":
			kwg["saas_db"] = DataBasePool().qa_saas
			kwg["nebula_db"] = DataBasePool().qa_nebula
		asyncio.create_task(ToolsSql.del_user_amount(env.value, source, **kwg))
		logger_.info(f"删除用户额度任务开始:{source}")
		asyncio.create_task(ToolsSql.del_credit_data(env.value, source, **kwg))
		logger_.info(f"删除授信数据任务开始:{source}")
	return {"code": 2000, "msg": "异步执行中"}


@router.post("/file", name="文件上传测试")
async def upload_file(file: UploadFile = File(...)):
	content = await file.read()
	return {"code": 2000, "file": content}


@router.post("/overdue/change", name="修改还款计划为逾期")
def change_overdue(item: OverdueItem):
	"""
	- environment: 要修改数据的环境 test/qa
	- project_id: 进件ID
	- period: 期数 有两种方式 1. 单期数 比如:n=1,2,3 代表从第一期开始，要逾期n期 2. 区间数 比如:5-7 代表从第5期开始[5，6，7]3期
	- start_date: 填写期数的最后一期还款计划时间 比如period=2 start_date=2020-12-24 则还款计划时间会变更为{1: 2020-11-24, 2:202012-24}
	"""
	if "-" in item.period:
		periods_list = item.period.split("-")
		pers = list(range(int(periods_list[0]), int(periods_list[1]) + 1))
		count = int(periods_list[1]) - int(periods_list[0])
	else:
		pers = list(range(1, int(item.period) + 1))
		count = int(item.period) - 1
	try:
		for per in pers:
			if per == pers[-1]:
				business_date = item.start_date
			else:
				business_date = str(item.start_date - relativedelta(months=count)).split(" ")[0]
			ToolsSql.change_repayment_plan_date(item.environment, per, business_date, item.project_id)
			count -= 1
		return {"code": 2000, "msg": "执行成功"}
	except Exception:
		return {"code": 5000, "msg": str(traceback.print_exc())}


# streamlit -> SAAS相关接口
@router.post("/offline_repay", name="线下还款流水推送")
def offline_repay(env: Env = Body(embed=True), asset_id: str = Body(embed=True), period: str = Body(embed=True), repay_time: str = Body(embed=True)):
	try:
		res = off_repay(env.value, asset_id, period, repay_time)
	except Exception as e:
		res = {"code": 4000, "errMsg": str(e)}
	return res


@router.post("/move_prod_data_to_test", name="转移生产换境数据至测试环境")
def move_prod_data_to_test(env: Env = Body(embed=True), asset_id_list: List[str] = Body(embed=True)):
	"""
	- env: 要移动到的换境
	- asset_id_list: 资产ID列表
	"""
	try:
		ToolsSql.move_prod_data_to_test(environment=env.value, asset_id_list=asset_id_list)
		return {"code": 2000, "msg": "执行成功"}
	except Exception as e:
		return {"code": 5000, "msg": str(e)}
